package com.xh.demo.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wen
 * @apiNote 全局网关资源流控处理器
 * @since 2021-12-12
 */
@Slf4j
@Configuration
public class BlockedExceptionHandlerConfig {

    @PostConstruct
    public void init() {
        GatewayCallbackManager.setBlockHandler((exchange, throwable) -> {
            Map<String, Object> responseBody = this.buildResponseBody(exchange, throwable);
            return ServerResponse.status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(responseBody));
        });
    }

    private Map<String, Object> buildResponseBody(ServerWebExchange exchange, Throwable throwable) {
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("code", 1001);
        responseBody.put("msg", "服务器繁忙，请稍后再试！");
        ServerHttpRequest request = exchange.getRequest();
        log.info("【GatewayBlocked-网关资源流控】【{}】", request.getPath().value());
        if (throwable instanceof BlockException) {
            // TODO do something
        }
        return responseBody;
    }

}
